<?php
class Catalog_MenuController extends Zend_Controller_Action
{
	public function preDispatch()
	{

	}
	public function init(){
        setlocale(LC_ALL, 'ru_RU.utf8');
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('get-comments', 'json')
            ->initContext();
	}

	public function mainAction()
	{
        $filters=array('page'=>array('HtmlEntities','StripTags','StringTrim'));
        $validators=array('page'=>array('Int'));
        $input=new Zend_Filter_Input($filters,$validators);
        $input->setData($this->getRequest()->getParams());

        if($input->isValid()){
            $q=Doctrine_Query::create()

                ->from('Myblog_Model_Articles a')
                ->leftJoin('a.Myblog_Model_Comments c')
                ->leftJoin('a.Myblog_Model_Bestweekarticles b')
                ->select('a.article_id,a.category_name,a.article,a.author,a.page,a.title,a.description,SUM(c.visibility) AS comments,a.created_dt,a.img,COUNT(b.article_id) AS views')
                ->where('a.page=?','main')
                ->addWhere('a.visibility=?','yes')
                //->useResultCache(true)
                ->groupby('a.article_id');

        $artCount = count($q->fetchArray());
        $perPage=6;
        $numPageLinks=5;
        $pager=new Doctrine_Pager($q,$input->page,$perPage);
        $result=$pager->execute(array(),Doctrine::HYDRATE_ARRAY);

            if(count($result)==0){
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Записей не обнаружено');
                $this->_redirect('/message');
            }
        $pagerRange=new Doctrine_Pager_Range_Sliding(
                array('chunk'=>$numPageLinks),$pager);
            $pagerUrlBase=$this->view->url(array(),'main',1) . "/{%page}";
            $pagerLayout=new Doctrine_Pager_Layout($pager,$pagerRange,$pagerUrlBase);
            $pagerLayout->setTemplate("<a class=btn href='{%url}'>{%page}</a>");

            $pagerLayout->setSelectedTemplate("<li class=active><a href='{%url}' >{%page}</a></li>");

            $pagerLayout->setSeparatorTemplate('');

            for($i=0;$i<count($result);$i++){
                $result[$i]['created_dt'] = strftime('%d %B %Y',time($result[$i]['created_dt']));
            }
            if($artCount > 6){

                $this->view->item=$result;//c
                $this->view->pages ='<span class="btn" disabled="disabled" style="font-size:10px;margin-right:3px;">Всего статей: '.$pager->getNumResults().'</span>'.'<a class="btn" href="/main/'.$pager->getFirstPage().'" title="В начало"><i class="icon-fast-backward"></i></a>'.'<a class="btn" href="/main/'.$pager->getPreviousPage().'" title=Предыдущая ><i class="icon-step-backward"></i></a>'.$pagerLayout ->display('',true).'<a class="btn" href="/main/'. $pager->getNextPage().'" title=Следующая><i class="icon-step-forward"></i></a>'.'<a class="btn" href="/main/'.$pager->getLastPage().'" title="В конец"><i class="icon-fast-forward"></i></a>'.'<span class="btn" disabled="disabled" style="font-size:10px;margin-left:3px;" >Всего страниц: '.$pager->getLastPage().'</span>';
            }
            elseif($input->page == $pager->getLastPage() && $artCount > 6 ){
                $this->view->item=$result;
                $this->view->pages ='<span class="pagecount">Всего статей: '.$pager->getNumResults().'<a href="/main/'.$pager->getFirstPage().'">В начало</a>'.'<a href="/main/'.$pager->getPreviousPage().'" title=Предыдущая >«</a>'.$pagerLayout ->display('',true).'<a href="/main/'. $pager->getNextPage().'" title=Следующая>»</a>'.'<a href="/main/'.$pager->getLastPage().'">В конец</a>'.'<span class="pagecount">Всего страниц: '.$pager->$pager->getLastPage().'</span>';
            }
            elseif($artCount <= 6)
            {
                $this->view->item=$result;
            }
            else{
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Записей не обнаружено');
                $this->_redirect('/message');
            }
		}else{
            throw new Zend_Controller_Action_Exception('Invalid input');
        }
    }
    public function getCommentsAction(){
        $q = Doctrine_Query::create()
            ->select('c.article_id')
            ->from('Myblog_Model_Comments c')
            ->where('c.visibility=?',1)
            ->fetchArray();
        foreach($q as $v=>$k){
            $this->view->$v= $k;
        }
    }
    public function catalogAction(){

        $filters=array('page'=>array('HtmlEntities','StripTags','StringTrim'));
        $validators=array('page'=>array('Int'));
        $input=new Zend_Filter_Input($filters,$validators);
        $input->setData($this->getRequest()->getParams());

        if($input->isValid()){
            $q=Doctrine_Query::create()

                ->from('Myblog_Model_Articles a')
                ->leftJoin('a.Myblog_Model_Comments c')
                ->leftJoin('a.Myblog_Model_Bestweekarticles b')
                ->select('a.article_id,a.category_name,a.article,a.author,a.page,a.title,a.description,a.created_dt,a.img,COUNT(c.article_id) AS comments,COUNT(b.article_id) AS views')
                ->where('a.page=?','articles')
                ->addWhere('a.visibility=?','yes')
                ->groupby('a.article_id');

            $artCount = count($q->fetchArray());
            $perPage=5;
            $numPageLinks=5;
            $pager=new Doctrine_Pager($q,$input->page,$perPage);
            $result=$pager->execute(array(),Doctrine::HYDRATE_ARRAY);
            if(count($result)==0){
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Записей не обнаружено');
                $this->_redirect('/message');
            }
            $pagerRange=new Doctrine_Pager_Range_Sliding(
                array('chunk'=>$numPageLinks),$pager);
            $pagerUrlBase=$this->view->url(array(),'catalog',1) . "/{%page}";
            $pagerLayout=new Doctrine_Pager_Layout($pager,$pagerRange,$pagerUrlBase);
            $pagerLayout->setTemplate("<a class=btn href='{%url}'>{%page}</a>");

            $pagerLayout->setSelectedTemplate("<li class=active><a href='{%url}' >{%page}</a></li>");
            $pagerLayout->setSeparatorTemplate('');



            for($i=0;$i<count($result);$i++){
                $result[$i]['created_dt'] = strftime('%d %B %Y',time($result[$i]['created_dt']));
            }

            if($artCount > 5 || $input->page == $pager->getLastPage() && $artCount > 5){

                $this->view->item=$result;
                $this->view->pages ='<span class="btn" disabled="disabled" style="font-size:10px;margin-right:3px;">Всего статей: '.$pager->getNumResults().'</span><a class="btn" href="/catalog/page/'.$pager->getFirstPage().'" title="В начало"><i class="icon-fast-backward"></i>'.'<a class="btn" href="/catalog/page/'.$pager->getPreviousPage().'" title=Предыдущая ><i class="icon-step-backward"></i></a>'.$pagerLayout ->display('',true).'<a class="btn" href="/catalog/page/'. $pager->getNextPage().'" title=Следующая><i class="icon-step-forward"></i></a>'.'<a class="btn" href="/catalog/page/'.$pager->getLastPage().'" title="В конец"><i class="icon-fast-forward"></i></a>'.'<span class="btn" disabled="disabled" style="font-size:10px;margin-left:3px;">Всего страниц: '.$pager->getLastPage().'</span>';

            }
            elseif($artCount <=5)
            {
                $this->view->item=$result;
            }
            else{
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Записей не обнаружено');
                $this->_redirect('/message');
            }

        }else{
            throw new Zend_Controller_Action_Exception('Invalid input');
        }
    }
    public function reviewsAction(){

        $filters=array('page'=>array('HtmlEntities','StripTags','StringTrim'));
        $validators=array('page'=>array('Int'));
        $input=new Zend_Filter_Input($filters,$validators);
        $input->setData($this->getRequest()->getParams());

        if($input->isValid()){
            $q=Doctrine_Query::create()

                ->from('Myblog_Model_Articles a')
                ->leftJoin('a.Myblog_Model_Comments c')
                ->leftJoin('a.Myblog_Model_Bestweekarticles b')
                ->select('a.article_id,a.category_name,a.article,a.author,a.page,a.title,a.description,a.created_dt,a.img,COUNT(c.article_id) AS comments,COUNT(b.article_id) AS views')
                ->where('a.page=?','reviews')
                ->addWhere('a.visibility=?','yes')
                ->groupby('a.article_id');

            $artCount = count($q->fetchArray());
            $perPage=5;
            $numPageLinks=5;
            $pager=new Doctrine_Pager($q,$input->page,$perPage);
            $result=$pager->execute(array(),Doctrine::HYDRATE_ARRAY);
            if(count($result)==0){
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Записей не обнаружено');
                $this->_redirect('/message');
            }
            $pagerRange=new Doctrine_Pager_Range_Sliding(
                array('chunk'=>$numPageLinks),$pager);
            $pagerUrlBase=$this->view->url(array(),'reviews',1) . "/{%page}";
            $pagerLayout=new Doctrine_Pager_Layout($pager,$pagerRange,$pagerUrlBase);
            $pagerLayout->setTemplate("<a class=btn href='{%url}'>{%page}</a>");

            $pagerLayout->setSelectedTemplate("<li class=active><a href='{%url}' class=active>{%page}</a></li>");
            $pagerLayout->setSeparatorTemplate('');

            for($i=0;$i<count($result);$i++){
                $result[$i]['created_dt'] = strftime('%d %B %Y',time($result[$i]['created_dt']));
            }

            if($artCount > 5 || $input->page == $pager->getLastPage() && $artCount > 5 ){

                $this->view->item=$result;
                $this->view->pages ='<span class="btn" disabled="disabled" style="font-size:10px;margin-right:3px;">Всего статей: '.$pager->getNumResults().'</span><a class="btn" href="/reviews/page/'.$pager->getFirstPage().'" title="В начало"><i class="icon-fast-backward"></i>'.'<a class="btn" href="/reviews/page/'.$pager->getPreviousPage().'" title=Предыдущая ><i class="icon-step-backward"></i></a>'.$pagerLayout ->display('',true).'<a class="btn" href="/reviews/page/'. $pager->getNextPage().'" title=Следующая><i class="icon-step-forward"></i></a>'.'<a class="btn" href="/reviews/page/'.$pager->getLastPage().'" title="В конец"><i class="icon-fast-forward"></i></a>'.'<span class="btn" disabled="disabled" style="font-size:10px;margin-left:3px;">Всего страниц: '.$pager->getLastPage().'</span>';

            }
            elseif($artCount <= 5)
            {
                $this->view->item=$result;
            }
            else{
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Записей не обнаружено');
                $this->_redirect('/message');
            }

        }else{
            throw new Zend_Controller_Action_Exception('Invalid input');
        }

    }
	public function aboutAction()
	{
	$q=Doctrine_Query::create()
		->from('Myblog_Model_Articles a')
		->where('a.url=?','/about')
		->addWhere('a.visibility=?','yes');
	$result=$q->fetchArray();
		if(count($result)>=1){
			$this->view->item=$result;
		}
		else{
			$this->_helper->getHelper('FlashMessenger')
					->addMessage('Записей не обнаружено');
			$this->_redirect('/message');
			}	
	}
	public function contactAction()
	{
		$get=new Myblog_Model_Admins;
		$form=new Myblog_Form_Contact;
		$to=$get->getEmail();
		$a=array('to'=>$get->getEmail()->email);
		$this->view->form=$form->populate($a);
	
		if($this->getRequest()->isPost())
		{
			if($this->view->form->isValid($this->getRequest()->getParams()))
			{
			$mail=new Zend_Mail();
			$mail->setBodyText($this->view->form->message);
			$mail->setFrom($this->view->form->from);
			$mail->addTo($to);
			$mail->setSubject($this->view->form->subject);

			$mail->send();

			$this->_helper->getHelper('FlashMessenger')
				->addMessage('Ваше сообщение отправлено.');
			//$this->_redirect('/contact/success');
			}	
		}
	}
	public function successAction()
	{
		if($this->_helper->getHelper('FlashMessenger')->getMessages()){
			$this->view->messages=$this->_helper
				->getHelper('FlashMessenger')->getMessages();
				header("Refresh:3;/");
				
			}else{
					$this->redirect('/');
				 }
	}
}
?>
